package com.zys.service.impl;

import java.util.List;
import java.util.ArrayList;

import com.zys.pojo.Menu;
import com.zys.dao.MenuDao;
import com.zys.service.MenuService;
import com.zys.utils.SerializeUtils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

@Transactional
@Service
public class MenuServiceImpl implements MenuService {
  @Autowired
  private MenuDao menuDao;
  @Autowired
  private JedisPool jedisPool;

  @Override
  public List<Menu> findAll() throws Exception {
    Jedis jedis = jedisPool.getResource();
    byte[] bytes = jedis.hget("menuList".getBytes(), "menuList".getBytes());

    // 判断 redis 是否有该有数据
    if (bytes != null && bytes.length > 0) {
      return  (ArrayList<Menu>) SerializeUtils.deserialize(bytes);
    }

    List<Menu> menuList = menuDao.findAll();
    for (Menu menu : menuList) {
      menu.setMenuItem(menuDao.findKidsById(menu.getId()));
    }

    jedis.hset("menuList".getBytes(), "menuList".getBytes(), SerializeUtils.serialize(menuList));

    return menuList;
  }
}
